package cn.com.easy.push.jiguan;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.easy.exception.BusinessException;
import cn.com.easy.push.jiguan.config.JiguanConfig;
import cn.com.easy.push.jiguan.dto.JiguanMessageDto;
import cn.com.easy.push.jiguan.enums.PlatformEnum;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.push.model.notification.PlatformNotification;

/**
 * 极光推送服务类 <br/>
 * 详参 :http://docs.jiguang.cn/jpush/server/3rd/java_sdk/
 * 
 * @author nibili 2017年6月6日
 * 
 */
public abstract class JiguanBaseService {

	private Logger logger = LoggerFactory.getLogger(JiguanBaseService.class);

	/**
	 * 获取极光配置
	 * 
	 * @return
	 * @author nibili 2017年6月6日
	 */
	public abstract JiguanConfig getJiguanConfig();

	/**
	 * 推送消息
	 * 
	 * @param jiguanMessageDto
	 * @throws BusinessException
	 * @author nibili 2017年6月7日
	 */
	public void sendMsg(JiguanMessageDto jiguanMessageDto) throws BusinessException {

		if (jiguanMessageDto.getPlatform() == null) {
			throw new BusinessException("平台不能为空");
		}
		if (StringUtils.isBlank(jiguanMessageDto.getAlert()) == true) {
			throw new BusinessException("推送内容不能为空");
		}
		// 极光配置
		JiguanConfig jiguanConfig = this.getJiguanConfig();
		//
		JPushClient jpushClient = new JPushClient(jiguanConfig.getSecret(), jiguanConfig.getAppKey(), null, ClientConfig.getInstance());
		//
		cn.jpush.api.push.model.PushPayload.Builder pushPayloadbuilder = PushPayload.newBuilder();
		{
			pushPayloadbuilder.setOptions(Options.newBuilder()
			// 此字段的值是用来指定本推送要推送的apns环境，false表示开发，true表示生产；对android和自定义消息无意义
					.setApnsProduction(jiguanMessageDto.getIosApns())
					// 此字段是给开发者自己给推送编号，方便推送者分辨推送记录
					.setSendno(jiguanMessageDto.getSendno())
					// 此字段的值是用来指定本推送的离线保存时长，如果不传此字段则默认保存一天，最多指定保留十天；
					.setTimeToLive(jiguanMessageDto.getTimeToLive()).build());
		}
		{
			// 一、平台
			pushPayloadbuilder = pushPayloadbuilder.setPlatform(jiguanMessageDto.getPlatform().getPlatform());
		}
		{
			// 二、杯签与别名 builder

			cn.jpush.api.push.model.audience.Audience.Builder audienceBuilder = null;
			// 标签
			if (CollectionUtils.isNotEmpty(jiguanMessageDto.getTags()) == true) {
				String[] tags = jiguanMessageDto.getTags().toArray(new String[] {});
				if (audienceBuilder == null) {
					audienceBuilder = Audience.newBuilder();
				}
				audienceBuilder.addAudienceTarget(AudienceTarget.tag(tags));
			}
			// 别名
			if (CollectionUtils.isNotEmpty(jiguanMessageDto.getAlias()) == true) {
				if (audienceBuilder == null) {
					audienceBuilder = Audience.newBuilder();
				}
				audienceBuilder.addAudienceTarget(AudienceTarget.alias(jiguanMessageDto.getAlias()));
			}
			if (audienceBuilder != null) {
				pushPayloadbuilder = pushPayloadbuilder.setAudience(audienceBuilder.build());
			} else {
				pushPayloadbuilder = pushPayloadbuilder.setAudience(Audience.all());
			}
		}
		// 三、通知 或者 消息
		if (jiguanMessageDto.getIsNotification() == true) {
			// a、通知
			Notification.Builder notificationBuilder = Notification.newBuilder();
			{
				if (jiguanMessageDto.getPlatform().getIndex() == PlatformEnum.ALL.getIndex()) {
					// 所有平台
					this.addAndroidNotification(notificationBuilder, jiguanMessageDto);
					this.addIosNotification(notificationBuilder, jiguanMessageDto);
				} else if (jiguanMessageDto.getPlatform().getIndex() == PlatformEnum.ANDROID.getIndex()) {
					// 安卓平台，标题
					this.addAndroidNotification(notificationBuilder, jiguanMessageDto);
				} else if (jiguanMessageDto.getPlatform().getIndex() == PlatformEnum.IOS.getIndex()) {
					// IOS平台
					this.addIosNotification(notificationBuilder, jiguanMessageDto);
				}
			}
			// 内容
			notificationBuilder.setAlert(jiguanMessageDto.getAlert());
			pushPayloadbuilder = pushPayloadbuilder.setNotification(notificationBuilder.build());
		} else {
			// b、消息

			// 标题 与 内容
			Message.Builder messageBuilder = Message.newBuilder();
			// 标题
			if (StringUtils.isNotEmpty(jiguanMessageDto.getTitle()) == true) {
				messageBuilder.setTitle(jiguanMessageDto.getTitle());
			}
			// 内容
			messageBuilder.setMsgContent(jiguanMessageDto.getAlert());
			pushPayloadbuilder = pushPayloadbuilder.setMessage(messageBuilder.build());
		}

		try {
			PushResult result = jpushClient.sendPush(pushPayloadbuilder.build());
			logger.info("Got result - " + result);

		} catch (APIConnectionException e) {
			// Connection error, should retry later
			logger.error("Connection error, should retry later", e);

		} catch (APIRequestException e) {
			// Should review the error, and fix the request
			logger.error("Should review the error, and fix the request", e);
			logger.info("HTTP Status: " + e.getStatus());
			logger.info("Error Code: " + e.getErrorCode());
			logger.info("Error Message: " + e.getErrorMessage());
		}
	}

	/**
	 * 添加安卓提醒
	 * 
	 * @param notificationBuilder
	 * @param jiguanMessageDto
	 * @author nibili 2017年6月7日
	 */
	private void addAndroidNotification(Notification.Builder notificationBuilder, JiguanMessageDto jiguanMessageDto) {
		// 安卓平台，标题
		AndroidNotification.Builder androidNotificationBuilder = AndroidNotification.newBuilder().setTitle(jiguanMessageDto.getTitle());
		androidNotificationBuilder.addExtras(jiguanMessageDto.getExtraParamMap());
		PlatformNotification platformNotification = androidNotificationBuilder.build();
		notificationBuilder.addPlatformNotification(platformNotification);
	}

	/**
	 * 添加ios提醒
	 * 
	 * @param notificationBuilder
	 * @param jiguanMessageDto
	 * @author nibili 2017年6月7日
	 */
	private void addIosNotification(Notification.Builder notificationBuilder, JiguanMessageDto jiguanMessageDto) {
		// IOS平台
		IosNotification.Builder iosNotificationBuilder = IosNotification.newBuilder();
		iosNotificationBuilder.addExtras(jiguanMessageDto.getExtraParamMap());
		PlatformNotification platformNotification = iosNotificationBuilder.build();
		notificationBuilder.addPlatformNotification(platformNotification);
	}
}
